<template>
	<view id="auto-wenjuan-manager">
		<wenjuan v-for="(wj,i) in wenjuanList" :key="wj.id" :ref="wj.id"
		 :type="wj.type" :title="wj.title" :hasOther="wj.hasOther"
		 :pickerType="typeof wj.subType === 'string'? wj.subType:'default'"
		 :pickerData="wj.defaultData"
		 :subTitle="wj.description" :mustAnswer="wj.mustAnswer"
		 :selectList="wj.defaultData"
		 :maxSelect="typeof wj.subType === 'number'?wj.subType:1"
		 :inputType="typeof wj.subType === 'string'?wj.subType:'text'"
		 :autoIndex="wj.autoIndex" :id="wj.id" @change="onchange">
			<view slot="beforeContent" v-if="wj.beforeHtml.length>0">{{wj.beforeHtml}}</view>
			<view v-if="wj.afterHtml.length>0">{{wj.afterHtml}}</view>
		</wenjuan>
		<button class="submitButton" @click="onSubmit">{{submitText}}</button>
		<uni-popup ref="mustAnswer_popup" type="message">
		    <uni-popup-message type="error" :message="'存在必答题目: '+mustAnswerButNotIndex+' 未完成!'" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	/**
	 * 简单问卷2.0-markdown解析工具
	 * @description 用于解析Markdown格式的问卷表单
	 * @property {String} md markdown文本
	 * @property {String} submitText 提交按钮文本 
	 * */
	import wenjuan from './gwh-wenjuan2.vue';
	export default {
		components:{
			wenjuan
		},
		props:{
			md:{
				type:String,
				default:''
			},
			submitText:{
				type:String,
				default:'提交表单'
			}
		},
		data(){
			return {
				wenjuanList:[],
				mustAnswerButNotIndex:0,
			}
		},
		mounted() {
			this.formWenjuan()
		},
		methods:{
			formPicker(str="", obj=[]){
				//去除首位中括号，
				str = str.replace(/^\[/g,'').replace(/\]$/g,'')
				//分割选项
				var childs = str.match(/[^,\[\]]+(\[.*\])*/g) || [];
				// console.log(childs)
				for (var i = 0; i< childs.length;i++){
					// 没有
					if (childs[i].replace(/[\n ]+/g,'').length == 0) continue;
					// 初始化当前选项
					var withoutChildstr = childs[i].replace(/\[.*(\])*/g,'').split(':')
					var theitem = {
						text:withoutChildstr[0],
						value:withoutChildstr.length>1?withoutChildstr[1]:withoutChildstr[0]
					}
					obj.push(theitem);
					var wenjuanTextList = childs[i].match(/\[.*(\])*/g) || [];
					if (wenjuanTextList && wenjuanTextList.length > 0) theitem.children=[];
					for (var j=0;j<wenjuanTextList.length;j++){
						this.formPicker(wenjuanTextList[j], theitem.children);
					}
				}
				return obj;
			},
			formWenjuan(){
				// 按照#分割题目
				var wenjuanTextList = this.md.match(/#{1,}[^#]*/g) || [];
				var theLastIndex = null;
				this.wenjuanList = [];
				// console.log(wenjuanTextList.length);
				for (var wi=0;wi<wenjuanTextList.length;wi++){
					var wjtext = wenjuanTextList[wi].replace(/\n+/g,'\n').replace(/ +/g,' ').replace(/\n$/g,'');
					// console.log(wjtext)
					var wenjuanOption = {
						id: 'auto-wenjuan-'+ wi + new Date().getTime(),
						title:"",
						autoIndex:'none',
						description:'',
						type:'none',
						subType:'',
						mustAnswer:false,
						beforeHtml:'',
						afterHtml:'',
						defaultData:[],
						hasOther:false,
						value:null,
					};
					//获取所有script并替换
					var scriptList = wjtext.match(/<[a-zA-Z0-9\-]*>(.*<\/[a-zA-Z0-9\-]>){0,1}/g);
					var withoutScript = wjtext.replace(/<[a-zA-Z0-9\-]*>(.*<\/[a-zA-Z0-9\-]>){0,1}/g,'__SCRIPT__')
					
					var splitTexts = withoutScript.split('\n');
					// 第一句是题目：
					var wenjuantitle = splitTexts[0]
					//题目
					wenjuanOption.title = wenjuantitle.replace(/[#@*]/g,'')
						.replace(/^ +/g,'').replace(/ +$/g, '');
					//判断是否必答
					wenjuanOption.mustAnswer = wenjuantitle.indexOf('**') >= 0;
					//获取当前题目自动编号
					var titleMark = wenjuantitle.match(/#(#*|@)/g)[0] || "#@";
					if (titleMark == '#@' ){
						wenjuanOption.autoIndex = 'none';
					}
					else if (theLastIndex == null || theLastIndex == '#@'){
						wenjuanOption.autoIndex = 'new';
					}
					else if (theLastIndex.length == titleMark.length){
						wenjuanOption.autoIndex = 'same';
					}
					else if (theLastIndex.length < titleMark.length){
						wenjuanOption.autoIndex = 'child';
					}
					else{
						wenjuanOption.autoIndex = 'parent-'+(theLastIndex.length-titleMark.length);
					}
					theLastIndex = titleMark;
					
					var usedScriptIndex = 0;
					//此后为题目私有内容
					for (var i=1;i<splitTexts.length;i++){
						// splitTexts[i] = splitTexts[i].replace(/__/g,' ');
						
						//判断前置自定义内容
						if(splitTexts[i].indexOf('<<')>=0){
							if(splitTexts[i].indexOf('__SCRIPT__')>=0){
								wenjuanOption.beforeHtml = scriptList[usedScriptIndex++]+splitTexts[i].replace(/__SCRIPT__/g,'').replace(/<</g,'');
							}
							else wenjuanOption.beforeHtml = splitTexts[i].replace(/<</g,'')
						}
						//判断后置自定义内容
						else if(splitTexts[i].indexOf('>>')>=0){
							if(splitTexts[i].indexOf('__SCRIPT__')>=0){
								wenjuanOption.afterHtml = scriptList[usedScriptIndex++]+splitTexts[i].replace(/__SCRIPT__/g,'').replace(/>>/g,'');
							}
							else wenjuanOption.afterHtml = splitTexts[i].replace(/>>/g,'')
						}
						//判断题型——选择题
						else if(splitTexts[i].indexOf('..')>=0){
							wenjuanOption.type = 'select'
							//分割选项
							var selectItems = splitTexts[i].split('..')
							wenjuanOption.defaultData = [];
							for (var j=0;j<selectItems.length;j++){
								if (selectItems[j].length == 0) continue;
								else if (selectItems[j].indexOf('??')>=0){
									//hasOther
									wenjuanOption.hasOther = true;
								}
								else if(selectItems[j].indexOf('__SCRIPT__')>=0){
									wenjuanOption.defaultData.push(scriptList[usedScriptIndex++]+selectItems[j].replace(/__SCRIPT__/g,''));
								}
								else wenjuanOption.defaultData.push(selectItems[j])
							}
						}
						else if(wenjuanOption.type == 'select' && splitTexts[i].search(/!\d+/g)>=0){
							//多选
							wenjuanOption.subType=parseInt(splitTexts[i].replace('!',''))
						}
						//判断题型——级联
						else if(splitTexts[i].indexOf('$$')>=0){
							wenjuanOption.type = 'picker'
							var jilianText = splitTexts[i].replace(/\${2,}/g,'').replace(/[\n ]+$/g,'');
							// console.log(jilianText.length)
							if(jilianText==='province' || jilianText==='p') wenjuanOption.subType = 'province';
							else if(jilianText==='country' || jilianText==='c') wenjuanOption.subType = 'country';
							else if(jilianText==='university' || jilianText==='u') wenjuanOption.subType = 'university';
							else if(jilianText==='work' || jilianText==='w') wenjuanOption.subType = 'work';
							else if(jilianText==='subjects' || jilianText==='s') wenjuanOption.subType = 'subjects';
							else wenjuanOption.subType = 'default';
							
							//当问卷类型为default时，尝试解析级联内容
							if (wenjuanOption.subType === 'default'){
								// wenjuanOption.description += ' 警告：暂不支持级联语法匹配！';
								// wenjuanOption.defaultData = [{text:'test',value:'0'}]
								//级联语法：[A,B[C,D],E:V1]
								//应该主动避免[和]不匹配情况
								while (
									(
										jilianText.length == 0 || 
										(jilianText.match(/\[/g) || []).length > (jilianText.match(/\]/g) || []).length
									) && i < splitTexts.length - 1 
								){
									jilianText += splitTexts[++i]
								}
								wenjuanOption.defaultData = []
								wenjuanOption.defaultData = this.formPicker(jilianText, wenjuanOption.defaultData);
							}
						}
						//判断题型——input
						else if(splitTexts[i].indexOf('::')>=0){
							wenjuanOption.type = 'input';
							if (splitTexts[i] === '::') wenjuanOption.subType = 'text';
							else if (splitTexts[i] === ':::' || splitTexts[i] === '::textarea') wenjuanOption.subType = 'textarea';
							else if (splitTexts[i] === '::p' || splitTexts[i] === '::password') wenjuanOption.subType = 'password';
							else if (splitTexts[i] === '::n' || splitTexts[i] === '::number') wenjuanOption.subType = 'number';
							else if (splitTexts[i] === '::id' || splitTexts[i] === '::idcard') wenjuanOption.subType = 'idcard';
							else if (splitTexts[i] === '::.' || splitTexts[i] === '::digit') wenjuanOption.subType = 'digit';
							else if (splitTexts[i] === '::ah' || splitTexts[i] === '::autoHeight') wenjuanOption.subType = 'autoHeight';
							else if (splitTexts[i] === '::dt' || splitTexts[i] === '::date') wenjuanOption.subType = 'date';
							else if (splitTexts[i] === '::tm' || splitTexts[i] === '::time') wenjuanOption.subType = 'time';
							else if (splitTexts[i] === '::dr' || splitTexts[i] === '::drive') wenjuanOption.subType = 'drive';
							else if (splitTexts[i] === '::lc' || splitTexts[i] === '::location') wenjuanOption.subType = 'location';
							else wenjuanOption.subType = 'text';
						}
						else {
							wenjuanOption.description += '\n'+splitTexts[i].toString()
						}
					}
					// console.log(wenjuanOption);
					this.wenjuanList.push(wenjuanOption)
				}
			},
			onchange(e){
				for (var i=0;i<this.wenjuanList.length;i++){
					if(e.id === this.wenjuanList[i].id){
						this.wenjuanList[i].value = e.value;
					}
				}
				this.$emit('change',e)
			},
			onSubmit(){
				var canSubmit = true;
				var that = this;
				for (var i=0;i<this.wenjuanList.length;i++){
					if(this.wenjuanList[i].type === 'none') continue;
					if(this.wenjuanList[i].mustAnswer && this.wenjuanList[i].value == null){
						canSubmit = false;
						var theWenjuan = this.$refs[this.wenjuanList[i].id][0];
						this.mustAnswerButNotIndex = theWenjuan.myIndex+theWenjuan.title;
						this.$refs.mustAnswer_popup.open()
						uni.createSelectorQuery().in(this).select('#auto-wenjuan-manager')
						 .boundingClientRect(res1=>{
							uni.createSelectorQuery().in(that).select('#'+that.wenjuanList[i].id)
							 .boundingClientRect(res2=>{
								// console.log(res1.top, res2.top)
								uni.pageScrollTo({
						　　　　　　 duration:0,//过渡时间必须为0，uniapp bug，否则运行到手机会报错
						　　　　　　 scrollTop:res2.top - res1.top,//滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
						　　　　 })
							}).exec()
						}).exec()
						break;
					}
				}
				if (canSubmit) this.$emit('submit',this.wenjuanList)
			}
		},
		watch:{
			md(newVal){
				this.formWenjuan()
			}
		}
	}
</script>

<style>
	.submitButton::after{
		border: 0px !important;
	}
	
	.submitButton{
		background-color: #007AFF;
		color: #FFFFFF;
		font-size: 20px;
	}
	
	.submitButton:active{
		background-color: #2C405A;
	}
</style>
